﻿using System;
using System.Configuration;
using FBGraph.Configuration;

namespace FBGraph.Web.Configuration
{
    /// <summary>Provides access to web-specific FBGraph.NET configuration settings.</summary>
    public static class FBGraphConfigurationManagerExtensions
    {
        /// <summary>Gets the <c>fbgraph/web/authorization</c> section of the FBGraph configuration, if it is defined.</summary>
        /// <param name="config">The <see cref="FBGraphConfigurationManager" /> that is being extended.</param>
        /// <returns>A <see cref="FBGraphAuthorizationSection" /> if the configuration defines one; otherwise, a null reference.</returns>
        public static FBGraphAuthorizationSection GetAuthorizationConfiguration(this FBGraphConfigurationManager config)
        {
            var apiSection = ConfigurationManager.GetSection("fbgraph/web/authorization");
            return (FBGraphAuthorizationSection)apiSection;
        }

        /// <summary>Gets the <c>fbgraph/web/authentication</c> section of the FBGraph configuration, if it is defined.</summary>
        /// <param name="config">The <see cref="FBGraphConfigurationManager" /> that is being extended.</param>
        /// <returns>A <see cref="FBGraphAuthenticationSection" /> if the configuration defines one; otherwise, a null reference.</returns>
        public static FBGraphAuthenticationSection GetAuthenticationConfiguration(this FBGraphConfigurationManager config)
        {
            var apiSection = ConfigurationManager.GetSection("fbgraph/web/authentication");
            return (FBGraphAuthenticationSection)apiSection;
        }

        /// <summary>Gets the <c>authUrl</c> defined in the FBGraph web configuration.</summary>
        /// <param name="config">The <see cref="FBGraphConfigurationManager" /> that is being extended.</param>
        /// <returns>The configured url if the configuration defines one; otherwise, a null reference.</returns>
        public static String GetAuthUrl(this FBGraphConfigurationManager config)
        {
            if (!String.IsNullOrEmpty(OverriddenAuthUrl)) return OverriddenAuthUrl;
            else
            {
                var authConfig = config.GetAuthenticationConfiguration();
                if (authConfig == null) return null;
                else return authConfig.AuthUrl;
            }
        }

        internal static String OverriddenAuthUrl { get { return ConfigurationManager.AppSettings["AuthUrl"]; } }
        internal static String OverriddenDefaultUrl { get { return ConfigurationManager.AppSettings["DefaultUrl"]; } }
    }
}